package com.lilin.gps;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.listener.SaveListener;

import com.lilin.gps.adapter.GPSInfoListAdapter;
import com.lilin.gps.model.GPSInfo;
import com.lilin.gps.service.GPSService;
import com.lilin.gps.utils.DateUtils;
import com.lilin.gps.utils.GPSUtils;
import com.lilin.gps.utils.LogUtils;
import com.lilin.gps.utils.NetUtils;
import com.lilin.gps.view.AboutActivity;
import com.pgyersdk.activity.FeedbackActivity;
import com.pgyersdk.feedback.PgyFeedback;
import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;

public class MainActivity extends Activity implements OnClickListener {
	// 设备信息
	TelephonyManager tm;
	Button serviceButton;
	// GPS显示列表
	ListView mListView;
	GPSInfoListAdapter adp;
	List<GPSInfo> mData = new ArrayList<GPSInfo>();
	//基本信息
	TextView info_txt;
	// gps的状态
	public static TextView gps_txt;	
	// 上报时间间隔（s）
	int uploadTime 	= 30;		
	// 提示消息
	public static String getFail 		= "GPS坐标获取失败，请稍后重试!";
	public static String getSuccess     = "GPS坐标获取成功!";
	public static String gpstips		= "GPS未启用，请打开!";
	// 是否开启GPS坐标上报线程
	public static Boolean isRefreshGPS 		 = false;
	// 是否开启GPS状态检查线程
	public static Boolean isRefreshGPSStatus = true;
	// SDCard写入路径
	public static String path;
	
	public static GPSInfo gps = new GPSInfo();
	
	String appversion;
	
	public static final int MSG_GPSINFO 	= 1; // 刷新GPS位置信息
	public static final int MSG_GPSStatus 	= 2; // 刷新GPS状态信息
	public static final int MSG_GPSERROR 	= 3; // 显示GPS获取失败信息
	
	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what == MSG_GPSINFO){
				dealGPSInfo();
			}else if(msg.what == MSG_GPSStatus){
				dealGPSStatus();
			}else if(msg.what == MSG_GPSERROR){
				dealGPSStatus();
			}
		};
	};
	
	// 处理GPS信息
	protected void dealGPSInfo() {
		GPSInfo gpsinfo = getGPS();
		if(gpsinfo == null){
			gps_txt.setVisibility(View.VISIBLE);
			gps_txt.setText(getFail);
			return;
		}
		gps_txt.setVisibility(View.GONE);
		// 刷新列表
		mData.add(0, gpsinfo);// 始终插入到第一个位置
		
		adp.notifyDataSetChanged();
		// 写入SDCard
		if (hasSDcard()) {
			LogUtils.Log2SDInfo(gps.GpsTime + " ( " + gps.Longitude + " , "+ gps.Latitude + " ) ", path);
		}
		//initInfo();
	}
	
	//显示GPS状态
	protected void dealGPSStatus() {
		initInfo();
	}

	/********************************************************************** GPS相关 开始 ********************************************************************/
	
	// 位置服务类
	private static String provider;
	private static LocationManager locationManager;
	// 监听位置变化的时间间隔:毫秒
	private static int requestlocationChangeTime 	 = 15*1000; 
	// 监听位置变化的距离间隔:5米
	private static int requestlocationChangeDistance = 2;
	// GPS状态
	private String gpsstatus;
	// 卫星状态
	private String statelliteStatus;
	// GSP位置是否发生改变
	private String locationIsChange = "当前位置";
	
	// 初始化LM
	private void initGPS(Context context) {
		locationManager = MyApplication.getLocationManager();
		provider 		= MyApplication.getGPSProvider();
		if(provider != null){
			// 添加GPS状态监听
			locationManager.addGpsStatusListener(gpsListener);
			// 添加位置变化监听
			// 参数1：位置提供器
			// 参数2：监听位置变化的时间间隔
			// 参数3：监听位置变化的距离间隔
			// 参数4：LocationListener监听器
			locationManager.requestLocationUpdates(provider, requestlocationChangeTime, requestlocationChangeDistance,locationListener);
		}
	}

	// 获取GPS位置信息
	public static GPSInfo getGPS() {
			GPSInfo gps = null;
			// 判断位置提供器 是否可用
			if (provider != null) {
				//获取缓存中的位置信息
				Location location = locationManager.getLastKnownLocation(provider);
				//采用GPS定位
				//location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
				if (location != null) {
					gps   = new GPSInfo();
					gps.Latitude  = location.getLatitude()+"";
					gps.Longitude = location.getLongitude()+"";
					gps.GpsTime	  = DateUtils.getCurrentTime();
				}
			}
			return gps;
	}

	// GPS位置变化监听事件
	private LocationListener locationListener = new LocationListener() {
		//当位置坐标发送改变时
		public void onLocationChanged(Location arg0) {
			if (arg0 != null) {
				locationIsChange = "坐标位置发生改变";
				Toast.makeText(getApplicationContext(), locationIsChange,Toast.LENGTH_SHORT).show();
				// 上报坐标
				dealGPSInfo();
			}
		}
		// Provider被disable时触发此函数，比如GPS被关闭  
		public void onProviderDisabled(String arg0) {
			// showInfo(null, -1);
		}
		// Provider被enable时触发此函数，比如GPS被打开
		public void onProviderEnabled(String arg0) {
			
		}
		// Provider的在可用、暂时不可用和无服务三个状态直接切换时触发此函数
		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
			
		}
	};
	
	// GPS状态监听,卫星数量
	GpsStatus.Listener gpsListener = new GpsStatus.Listener() {
		public void onGpsStatusChanged(int event) {
			switch (event) {
			// 第一次定位
			case GpsStatus.GPS_EVENT_FIRST_FIX:
				Log.i("andli", "第一次定位");
				gpsstatus = "第一次定位";
				break;
			// 卫星状态改变
			case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
				//Log.i("andli", "卫星状态改变");
				gpsstatus = "卫星状态改变";
				// 获取当前状态
				GpsStatus gpsStatus = locationManager.getGpsStatus(null);
				if(gpsstatus == null){
					return;
				}
				// 获取卫星颗数的默认最大值
				int maxSatellites = gpsStatus.getMaxSatellites();
				// 创建一个迭代器保存所有卫星
				Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();
				int count = 0;
				while (iters.hasNext() && count <= maxSatellites) {
					//GpsSatellite s = iters.next();
					count++;
				}
				statelliteStatus = "搜索到" + count + "颗卫星";
				break;
			// 定位启动
			case GpsStatus.GPS_EVENT_STARTED:
				Log.i("andli", "定位启动");
				gpsstatus = "定位启动";
				break;
			// 定位结束
			case GpsStatus.GPS_EVENT_STOPPED:
				Log.i("andli", "定位结束");
				gpsstatus = "定位结束";
				break;
			}
		};
	};
	/********************************************************************** GPS相关 结束 ********************************************************************/

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mainactivity);
		
		// 隐藏输入法
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		
		appversion = MyApplication.appInfo.versionName;
		setTitle("GPS定位测试 V"+appversion);
		
		// 初始化Bmob
        Bmob.initialize(this, Constants.BMOB_APPID);
        // 检查版本更新
        checkAPKVersion(false);
		tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
		// 初始化GPS
		initGPS(this);
		
		path = Environment.getExternalStorageDirectory().toString()+"/gpstest";
		initUI();
		
		if(isRefreshGPS == false){
			dealGPSInfo();
		}
		
		// 开启GPS坐标上报线程
		new Thread() {
			public void run() {
				while (isRefreshGPS) {
					Message msg = new Message();
					msg.what = 1;
					handler.sendMessage(msg);
					
					try {
						sleep(1000*uploadTime);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
		
		// 开启GPS状态检查线程
		new Thread() {
			public void run() {
				while (isRefreshGPSStatus) {
					Message msg = new Message();
					msg.what = 2;
					handler.sendMessage(msg);

					try {
						sleep(1000 * 15);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
		
	}

	

	private void initUI() {
		serviceButton 	= (Button)findViewById(R.id.serviceButton);
		mListView   	= (ListView)findViewById(R.id.listview);
		
		gps_txt     	= (TextView)findViewById(R.id.gps_txt);
		info_txt		= (TextView)findViewById(R.id.info_txt);
		gps_txt.setTextColor(Color.RED);
		
		serviceButton.setText(startUpload);
		serviceButton.setOnClickListener(this);
		stopService();
		
		adp = new GPSInfoListAdapter(mData, this);
		mListView.setAdapter(adp);
		
		initInfo();
	}
	
	//初始化基本信息
	public void initInfo(){
		String info = "";
		if(checkGPSStatus()){
			info += "当前网络环境: "+NetUtils.GetNetworkType()+"<br/>";
			info += "当前系统版本: "+android.os.Build.VERSION.RELEASE+"<br/>";
			info += "当前手机型号: "+android.os.Build.MODEL+"<br/>";
			info += "GPS已开启<br/>";
			info += "GPS刷新的时间间隔: "+uploadTime+"秒<br/>";
			info += "GPS数据存储的路径: "+path+"<br/>";
			info += "<br/>";
			info += "GPS监听位置变化的时间间隔: "+requestlocationChangeTime+" 豪秒<br/>";
			info += "GPS监听位置变化的距离间隔: "+requestlocationChangeDistance+" 米<br/>";
			info += "<br/>";
			info += "GPS状态刷新的时间间隔:15秒<br/>";
			info += "GPS状态: "+gpsstatus+"<br/>";
			info += "卫星状态: "+statelliteStatus+"<br/>";
			info += "位置状态: "+locationIsChange+"<br/>";
			info += "<br/>";
			info += "当前GPS坐标: ";
			
			gps.InfoType 			= "";
			gps.GpsTime  			= DateUtils.getCurrentTime();
			gps.DeviceID 			= tm.getDeviceId();
			gps.DeviceSimOperator 	= GPSUtils.getSimOperatorName(tm.getSimOperator());
			gps.DeviceNetworkType 	= NetUtils.GetNetworkType();
			gps.DevicePhone 		= tm.getLine1Number();
			
			// SDK版本
			gps.OSSDKVersion 		= android.os.Build.VERSION.SDK_INT+"";
			// 系统版本
			gps.OSVersion 			= android.os.Build.VERSION.RELEASE+"";
			// 手机型号
			gps.OSModel 			= android.os.Build.MODEL+"";
			
		}else{
			info += gpstips;
		}
		info_txt.setText(Html.fromHtml(info));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.serviceButton:
			controlGPSService();
		default:
			break;
		}
	}
	String startUpload = "开启位置上报";
	String stopUpload  = "停止位置上报";
	// 控制后台GPS服务
	private void controlGPSService() {
		if(serviceButton.getText().equals(startUpload)){
			// 启动GPS定位服务
			Intent gpsService = new Intent(this,GPSService.class);
			startService(gpsService);
			serviceButton.setText(stopUpload);
			serviceButton.setBackgroundColor(Color.RED);
			serviceButton.setTextColor(Color.WHITE);
		}else{
			stopService();
		}
		
	}

	private void stopService() {
		// 关闭GPS通知栏
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notificationManager.cancel(GPSService.GPSNOTIFICATIONID);
		// 停止GPS定位服务
		Intent gpsService = new Intent(this, GPSService.class);
		stopService(gpsService);
		serviceButton.setText(startUpload);
		serviceButton.setBackgroundColor(Color.LTGRAY);
		serviceButton.setTextColor(Color.BLACK);
	}

	public void onResume() {
		if(!checkGPSStatus()){
			Toast.makeText(this,gpstips, Toast.LENGTH_SHORT).show();
		}
		//蒲公英反馈对话框设置：摇一摇的方式
		// // 自定义摇一摇的灵敏度，默认为950，数值越小灵敏度越高。
		// PgyFeedbackShakeManager.setShakingThreshold(1000);
		// // 以对话框的形式弹出
		// PgyFeedbackShakeManager.register(MainActivity.this);
		// // 打开沉浸式,默认为false
		// // FeedbackActivity.setBarImmersive(true);
		// PgyFeedbackShakeManager.register(MainActivity.this, false);
        
		super.onResume();
	}

	public void onPause() {
		if(!checkGPSStatus()){
			Toast.makeText(this,gpstips, Toast.LENGTH_SHORT).show();
		}
		super.onPause();
	}
	
	
	@Override
	protected void onDestroy() {
		isRefreshGPS 		= false;
		isRefreshGPSStatus 	= false;
		if(locationManager !=null){
			locationManager.removeGpsStatusListener(gpsListener);
			locationManager.removeUpdates(locationListener);
			locationManager = null;
		}
		//PgyFeedbackShakeManager.unregister();
		
		stopService();
		super.onDestroy();
	}
	
	//检查GPS模块是否可用
	public boolean checkGPSStatus(){
		LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);// 获取位置管理服务
		if (lm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
			return true;
		} else {
			return false;
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			new AlertDialog.Builder(MainActivity.this)
					.setTitle("提示")
					.setMessage("确定退出吗?")
					.setPositiveButton("是",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface arg0,int arg1) {
									finish();
									System.exit(0);
								}
							}).setNegativeButton("否", null).create().show();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "设置");
		menu.add(0, 1, 1, "更新");
		menu.add(0, 2, 2, "反馈");
		menu.add(0, 3, 3, "关于");
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		Intent intent;
		switch (item.getItemId()) {
		//设置
		case 0:
			intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
			startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
			break;
		//更新
		case 1:
			checkAPKVersion(true);
			break;
		//反馈:以对话框的形式弹出
		case 2:
			// 打开沉浸式,默认为false
			//FeedbackActivity.setBarImmersive(true);
			// 设置顶部导航栏和底部bar的颜色
			FeedbackActivity.setBarBackgroundColor("#ff0000");
			// 设置顶部按钮和底部按钮按下时的反馈色
			FeedbackActivity.setBarButtonPressedColor("#ff0000");
			// 设置颜色选择器的背景色
			FeedbackActivity.setColorPickerBackgroundColor("#ff0000");
			PgyFeedback.getInstance().showActiivty(MainActivity.this);
			break;
		//关于
		case 3:
			intent = new Intent(MainActivity.this,AboutActivity.class);
			startActivity(intent);
			PgyUpdateManager.register(this);
			break;
		default:
			break;
		}

		return super.onMenuItemSelected(featureId, item);
	}
	
	// 判断是否有内存卡
	public static boolean hasSDcard() {
		if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) { // sd卡存在
			return true;
		}
		return false;
	}
	String downURL;
	//注册蒲公英相关服务
	public void checkAPKVersion(final boolean isshow){
		// 带回调的版本更新检查
        PgyUpdateManager.register(MainActivity.this,new UpdateManagerListener() {
					@Override
					public void onUpdateAvailable(final String result) {
						Log.i("andli","返回结果："+result);
						// 将新版本信息封装到AppBean中
				        final AppBean appBean = getAppBeanFromString(result);
				        if(!appBean.getVersionName().equals(appversion)){
				        	new AlertDialog.Builder(MainActivity.this)
				            .setTitle("提示更新")
				            .setMessage(appBean.getReleaseNote())
				            .setNegativeButton( "确定",new DialogInterface.OnClickListener() {
				                        @Override
				                        public void onClick(DialogInterface dialog,int which) {
				                            startDownloadTask( MainActivity.this,appBean.getDownloadURL());
				                        }
				             })
				             .setNeutralButton("取消", null)
				             .show();
				        }
					}
					@Override
					public void onNoUpdateAvailable() {
						if(isshow){
							Toast.makeText(getApplicationContext(), "当前版本最新!", Toast.LENGTH_SHORT).show();
						}
					}
		});
	}
	
	// 上传坐标到Bmob服务器
	public static void uploadGPS() {
		GPSInfo gpsinfo = getGPS();
		if(gpsinfo != null){
			gpsinfo.InfoType 			= gps.InfoType;
			gpsinfo.GpsTime  			= DateUtils.getCurrentTime();
			gpsinfo.DeviceID 			= gps.DeviceID;
			gpsinfo.DeviceSimOperator 	= gps.DeviceSimOperator;
			gpsinfo.DeviceNetworkType 	= gps.DeviceNetworkType;
			gpsinfo.DevicePhone 		= gps.DevicePhone;
			//SDK版本
			gpsinfo.OSSDKVersion 		= gps.OSSDKVersion;
			//系统版本
			gpsinfo.OSVersion 			= gps.OSVersion;
			//手机型号
			gpsinfo.OSModel 			= gps.OSModel;
			// 上传到服务器
			gpsinfo.save(MyApplication.getContext(), new SaveListener() {
				@Override
				public void onSuccess() {
					Log.i("andli", "坐标上报成功!"+DateUtils.getCurrentTime());
				}
				@Override
				public void onFailure(int arg0, String arg1) {
					Log.i("andli", "坐标上报失败! " + DateUtils.getCurrentTime() +" error: "+ arg1);
				}
			});
		} else {
			//不能在子线程中更新UI
//			gps_txt.setVisibility(View.VISIBLE);
//			gps_txt.setText(getFail);
		}
	}
}
